//
//  YJHomePageViewController.m
//  SnackCourier
//
//  Created by qianfeng01 on 15/7/17.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "YJHomePageViewController.h"
#import "UIImageView+WebCache.h"

#import "YJBannerListModel.h"
#import "YJSalesListModel.h"
#import "YJSalesTopicListModel.h"
#import "YJSenceListModel.h"
#import "YJReportListModel.h"
#import "YJRecommendShopListModel.h"


#import "YJBannerListCell.h"
#import "YJImmediatelygrabCell.h"
#import "YJSalesTopicListCell.h"
#import "YJSenceListCell.h"
#import "YJRecommendShopListCell.h"
#import "YJReportListcell.h"

#import "YJHeaderController.h"
#import "YJImmediatelygrabController.h"
#import "YJBasicinformationController.h"
#import "YJMoreinformationController.h"
#import "YJSpecificationController.h"
#import "YJSalesTopicListController.h"

#import "YJSenceListController.h"
#import "YJMoreViewController.h"


@interface YJHomePageViewController ()<UITableViewDataSource,UITableViewDelegate>



@property (nonatomic,strong)NSMutableArray *bannerListArray;
@property (nonatomic,strong)NSMutableArray *salesTopicListArray;
@property (nonatomic,strong)NSMutableArray *senceListArray;
@property (nonatomic,strong)NSMutableArray *recommendShopListArray;
@property (nonatomic,strong)NSMutableArray *salesListArray;
@property (nonatomic,strong)NSMutableArray *reportListArray;
@property (nonatomic,strong)NSMutableArray *HeaderViewTistArray;

@property (nonatomic)UIScrollView *scorollView;
@property (nonatomic)UITableView *tableView;
@property (nonatomic)NSMutableArray *dataArray;
@property (nonatomic)AFHTTPRequestOperationManager *manager;
@end
@implementation YJHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [[NSMutableArray alloc] init];
    
    self.HeaderViewTistArray =[[NSMutableArray alloc] initWithObjects:@"",@"特惠马上抢",@"精选促销",@"不知道买什么",@"什么值得买",@"好店推荐", nil];
    self.bannerListArray = [[NSMutableArray alloc] init];
    self.salesTopicListArray = [[NSMutableArray alloc] init];
    self.senceListArray = [[NSMutableArray alloc] init];
    self.recommendShopListArray = [[NSMutableArray alloc] init];
    self.salesListArray = [[NSMutableArray alloc] init];
    self.reportListArray = [[NSMutableArray alloc] init];
    
    [self createTableView];
    [self createHttpRequest];
    
    [self loadData:kHomePageUrl];
    
    [self refreshData:kHomePageUrl];
    

}

-(void) createTableView{
    
    self.tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64) style:(UITableViewStyleGrouped)];
    self.tableView.dataSource =self;
    self.tableView.delegate =self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"YJBannerListCell" bundle:nil] forCellReuseIdentifier:@"YJBannerListCell" ];
    [self.tableView registerNib:[UINib nibWithNibName:@"YJImmediatelygrabCell" bundle:nil] forCellReuseIdentifier:@"YJImmediatelygrabCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YJSalesTopicListCell" bundle:nil] forCellReuseIdentifier:@"YJSalesTopicListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YJSenceListCell" bundle:nil] forCellReuseIdentifier:@"YJSenceListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YJReportListcell" bundle:nil] forCellReuseIdentifier:@"YJReportListcell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YJRecommendShopListCell" bundle:nil] forCellReuseIdentifier:@"YJRecommendShopListCell"];
    
    [self.view addSubview:self.tableView];
}

-(void)loadData:(NSString *)urlStr{
    NSString *path =[YJHelper getFullPathWithFile:urlStr];
    BOOL isExist =[[NSFileManager defaultManager]fileExistsAtPath:path];
    BOOL isTimeout =[YJHelper isTimeOutWithFile:urlStr timeOut:24*60*60];
    if ((isExist==YES)&&(isTimeout==NO)) {
        NSData *data =[NSData dataWithContentsOfFile:[YJHelper getFullPathWithFile:urlStr]];
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
            [self.bannerListArray removeAllObjects];
            [self.salesListArray removeAllObjects];
            [self.salesTopicListArray removeAllObjects];
            [self.senceListArray removeAllObjects];
            [self.reportListArray removeAllObjects];
            [self.recommendShopListArray removeAllObjects];
            
        }
        NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dict =dicts[@"data"];
        NSArray *bannerListArray = dict[@"bannerList"];
        NSArray *salesTopicListArray =dict[@"salesTopicList"];
        NSArray *senceListArray =dict[@"senceList"];
        NSArray *recommendShopListArray =dict[@"recommendShopList"];
        NSArray *salesListArray =dict[@"salesList"];
        NSDictionary *reportDic =dict[@"reportList"];
        for (NSDictionary *dict in bannerListArray) {
            YJBannerListModel *model =[[YJBannerListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.bannerListArray addObject:model];
        }
        [self.dataArray addObject:self.bannerListArray];
        for (NSDictionary *dict in salesListArray) {
            YJSalesListModel *model =[[YJSalesListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.salesListArray addObject:model];
            
        }
        [self.dataArray addObject:self.salesListArray];
        for (NSDictionary *dict in salesTopicListArray) {
            YJSalesTopicListModel *model =[[YJSalesTopicListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.salesTopicListArray addObject:model];
            
        }
        [self.dataArray addObject:self.salesTopicListArray];
        for (NSDictionary *dict in senceListArray) {
            YJSenceListModel *model =[[YJSenceListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.senceListArray addObject:model];
            
        }
        [self.dataArray addObject:self.senceListArray];
        
        YJReportListModel*model =[[YJReportListModel alloc] init];
        [model setValuesForKeysWithDictionary:reportDic];
        [self.reportListArray addObject:model];
        
        [self.dataArray addObject:self.reportListArray];
        for (NSDictionary *dict in recommendShopListArray) {
            YJRecommendShopListModel*model =[[YJRecommendShopListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.recommendShopListArray addObject:model];
            
        }
        [self.dataArray addObject:self.recommendShopListArray];
        [self.tableView reloadData];
        [self endRefreshing];
        return;
    }
    
    
    __weak typeof (self) weakSelf=self;
    [self.manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (responseObject) {
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.bannerListArray removeAllObjects];
            [weakSelf.salesListArray removeAllObjects];
            [weakSelf.salesTopicListArray removeAllObjects];
            [weakSelf.senceListArray removeAllObjects];
            [weakSelf.reportListArray removeAllObjects];
            [weakSelf.recommendShopListArray removeAllObjects];
            
            NSDictionary *dicts =[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dict =dicts[@"data"];
            NSArray *bannerListArray = dict[@"bannerList"];
            NSArray *salesTopicListArray =dict[@"salesTopicList"];
            NSArray *senceListArray =dict[@"senceList"];
            NSArray *recommendShopListArray =dict[@"recommendShopList"];
            NSArray *salesListArray =dict[@"salesList"];
            NSDictionary *reportDic =dict[@"reportList"];
            for (NSDictionary *dict in bannerListArray) {
                YJBannerListModel *model =[[YJBannerListModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [self.bannerListArray addObject:model];

            }
            [weakSelf.dataArray addObject:weakSelf.bannerListArray];
            for (NSDictionary *dict in salesListArray) {
                YJSalesListModel *model =[[YJSalesListModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [self.salesListArray addObject:model];
                
            }
            [weakSelf.dataArray addObject:weakSelf.salesListArray];
            for (NSDictionary *dict in salesTopicListArray) {
               YJSalesTopicListModel *model =[[YJSalesTopicListModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [weakSelf.salesTopicListArray addObject:model];
                
            }
            [weakSelf.dataArray addObject:weakSelf.salesTopicListArray];
            for (NSDictionary *dict in senceListArray) {
                YJSenceListModel *model =[[YJSenceListModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [weakSelf.senceListArray addObject:model];
                
            }
            [weakSelf.dataArray addObject:weakSelf.senceListArray];
            
            YJReportListModel*model =[[YJReportListModel alloc] init];
            [model setValuesForKeysWithDictionary:reportDic];
            [weakSelf.reportListArray addObject:model];

            [weakSelf.dataArray addObject:weakSelf.reportListArray];
            for (NSDictionary *dict in recommendShopListArray) {
                YJRecommendShopListModel*model =[[YJRecommendShopListModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [weakSelf.recommendShopListArray addObject:model];
                
            }
            [weakSelf.dataArray addObject:weakSelf.recommendShopListArray];
            [weakSelf.tableView reloadData];
        }
        [weakSelf endRefreshing];
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         
    }];
}
-(void)refreshData:(NSString *)urlStr{
    __weak typeof(self) weakSelf=self;//声明弱引用
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //重新下载数据
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;//标记正在刷新
        [weakSelf loadData:urlStr];
    }];
}

-(void)endRefreshing{
    if (self.isRefreshing) {
        //正在刷新，就结束刷新
        self.isRefreshing=NO;//标记刷新结束
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section ==5) {
        NSArray *array =self.dataArray[section];
        return [array count];
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        YJBannerListCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJBannerListCell" forIndexPath:indexPath];
        [cell showDataWithArray:self.bannerListArray myblock:^(NSString *str) {
            YJHeaderController *controller =[[YJHeaderController alloc] init];
            controller.linkUrl =str;
            [self.navigationController pushViewController:controller animated:YES];
        }];
        return cell;
    }else if (indexPath.section==1) {
        YJImmediatelygrabCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJImmediatelygrabCell"forIndexPath:indexPath];
        [cell showDataWithArray:self.salesListArray myBlock:^(NSInteger id) {
            YJImmediatelygrabController *controller =[self createVC:id];
            controller.title =@"商品详情";
            [self.navigationController pushViewController:controller animated:YES];
        }];
        return cell;
    }else if(indexPath.section ==2){
        YJSalesTopicListCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJSalesTopicListCell"forIndexPath:indexPath ];
        [cell showDataWithArray:self.salesTopicListArray myblock:^(YJSalesTopicListModel *model) {
            YJSalesTopicListController *controller = [[YJSalesTopicListController alloc] init];
            controller.model =model;
            [self.navigationController pushViewController:controller animated:YES];
            
        }];
        return cell;
    }else if(indexPath.section ==3){
        YJSenceListCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJSenceListCell"forIndexPath:indexPath ];
        [cell showDataWithArray:self.senceListArray myblock:^(YJSenceListModel *model) {
            YJSenceListController *controller =[[YJSenceListController alloc] init];
            controller.sencelmodel =model;
            
        [self.navigationController pushViewController:controller animated:YES];
        }];
        return cell;
    }else if(indexPath.section ==4){
        YJReportListcell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJReportListcell"forIndexPath:indexPath ];
        YJReportListModel *model =self.reportListArray[0];
        
        [cell showDataWithModel:model];
        return cell;
    }else {
        YJRecommendShopListCell *cell=[tableView dequeueReusableCellWithIdentifier:@"YJRecommendShopListCell" forIndexPath:indexPath ];
        YJRecommendShopListModel *mode =self.recommendShopListArray[indexPath.row];
        [cell showDataWithModel:mode];
        return cell;
    }
    return nil;
}
-(YJImmediatelygrabController *)createVC:(NSInteger)id{
    NSMutableArray *controllers=[[NSMutableArray alloc] init];
    NSMutableArray *titles =[[NSMutableArray alloc] init];
    
    YJBasicinformationController *View1 =[[YJBasicinformationController alloc] init];
    NSString *title1 =@"基本信息";
    View1.urlStr =[NSString stringWithFormat:kImmediatelygrabUrl,(long)id];
    [controllers addObject:View1];
    [titles addObject:title1];
    
    YJMoreinformationController *View2 =[[YJMoreinformationController alloc] init];
    NSString *title2 =@"更多详情";
    View2.urlStr =[NSString stringWithFormat:kImmediatelygrabUrl,(long)id];
    [controllers addObject:View2];
    [titles addObject:title2];
    
    YJSpecificationController *View3 =[[YJSpecificationController alloc] init];
    NSString *title3 =@"规格参数";
    
    View3.urlStr =[NSString stringWithFormat:kImmediatelygrabUrl,(long)id];
    [titles addObject:title3];
    [controllers addObject:View3];
    YJImmediatelygrabController *controller =[[YJImmediatelygrabController alloc] initWithViewControllers:controllers andTheirTitles:titles];
    controller.pageAnimatable =YES;
    controller.menuItemWidth =self.view.frame.size.width/3.0;
    return controller;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==5) {
        return 80;
    }else if(indexPath.section==4){
        return 180;
    }
    return 150;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return nil;
    }else if (section==4) {
        UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        UIView *redView =[[UIView alloc] initWithFrame:CGRectMake(8, 5, 4, 20)];
        redView.backgroundColor =[UIColor redColor];
        redView.layer.masksToBounds =YES;
        redView.layer.cornerRadius =2;
        [view addSubview:redView];
        
        UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(redView.frame.size.width+10, 5, 222, 20)];
        label.text =self.HeaderViewTistArray[section];
        [view addSubview:label];
        
        UIButton *button =[UIButton buttonWithType:(UIButtonTypeSystem)];
        button.frame=CGRectMake(self.view.frame.size.width-100, 0, 100, 30);
        UIImage *image =[UIImage imageNamed:@"more"];
        image =[image imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        [button setImage:image forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(moreClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [view addSubview:button];
        return view;
    }else{
        UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        UIView *redView =[[UIView alloc] initWithFrame:CGRectMake(8, 5, 4, 20)];
        redView.backgroundColor =[UIColor redColor];
        redView.layer.masksToBounds =YES;
        redView.layer.cornerRadius =2;
        [view addSubview:redView];
        
        UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(redView.frame.size.width+10, 5, 222, 20)];
        label.text =self.HeaderViewTistArray[section];
        [view addSubview:label];
        return view;
    }
    return nil;
}

-(void)moreClick:(UIButton *)button{
    YJMoreViewController *controller =[[YJMoreViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YJHeaderController *controller =[[YJHeaderController alloc] init];
    if (indexPath.section ==4) {
        YJReportListModel *model=self.reportListArray[indexPath.row];
        controller.linkUrl =model.linkUrl;
        [self.navigationController pushViewController:controller animated:YES];
    }else if(indexPath.section==5){
        YJRecommendShopListModel * model =self.recommendShopListArray[indexPath.row];
        controller.linkUrl =model.linkUrl;
        [self.navigationController pushViewController:controller animated:YES];
        
    }
}


@end
